package com.example.fairplay.newfpregistration.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.camera.CameraInterface;
import com.example.fairplay.newfpregistration.camera.FacePicInterface;
import com.example.fairplay.newfpregistration.camera.FragmentCamera;
import com.example.fairplay.newfpregistration.util.StatusBarCompat;
import com.example.mylibrary.config.Config;
import com.example.mylibrary.config.Content;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DBManager;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.tcp.PackageHeadInfo;
import com.example.mylibrary.tcp.ResultPackage;
import com.example.mylibrary.tcp.SocketClient;
import com.example.mylibrary.tcp.TCPConst;
import com.example.mylibrary.util.DateUtils;
import com.example.mylibrary.util.ImageUtil;
import com.example.mylibrary.util.PreferencesUtils;
import com.example.mylibrary.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.example.mylibrary.config.Content.idCar;
import static com.example.mylibrary.tcp.PackageHeadInfo.g_SepFlag1;
import static com.example.mylibrary.tcp.TCPConst.MAX_RECORD_COUNT;

/**
 * Created by fairplay on 2018/6/11.
 */

public class DistinguishFaceActivity extends BaseActivity2 implements FacePicInterface {
	@Bind(R.id.tv_name)
	TextView tvName;
	@Bind(R.id.ed_name)
	EditText edName;
	@Bind(R.id.ly_name)
	LinearLayout lyName;
	@Bind(R.id.tv_nation)
	TextView tvNation;
	@Bind(R.id.ed_nation)
	EditText edNation;
	@Bind(R.id.ly_nation)
	LinearLayout lyNation;
	@Bind(R.id.tv_birthday)
	TextView tvBirthday;
	@Bind(R.id.ed_birthday)
	EditText edBirthday;
	@Bind(R.id.ly_birthday)
	LinearLayout lyBirthday;
	@Bind(R.id.tv_school)
	TextView tvSchool;
	@Bind(R.id.ed_school)
	EditText edSchool;
	@Bind(R.id.ly_school)
	LinearLayout lySchool;
	@Bind(R.id.tv_sex)
	TextView tvSex;
	@Bind(R.id.ed_sex)
	EditText edSex;
	@Bind(R.id.ly_sex)
	LinearLayout lySex;
	@Bind(R.id.tv_idcard)
	TextView tvIdcard;
	@Bind(R.id.ed_idcard)
	EditText edIdcard;
	@Bind(R.id.ly_idcard)
	LinearLayout lyIdcard;
	@Bind(R.id.tv_address)
	TextView tvAddress;
	@Bind(R.id.ed_address)
	EditText edAddress;
	@Bind(R.id.ly_address)
	LinearLayout lyAddress;
	@Bind(R.id.tv_stuID)
	TextView tvStuID;
	@Bind(R.id.ed_stuID)
	EditText edStuID;
	@Bind(R.id.ly_stuID)
	LinearLayout lyStuID;
	@Bind(R.id.iv_face1)
	ImageView ivFace1;
	@Bind(R.id.iv_face2)
	ImageView ivFace2;
	@Bind(R.id.iv_face3)
	ImageView ivFace3;
	//	@Bind(R.id.iv_finger1)
//	ImageView ivFinger1;
//	@Bind(R.id.iv_finger2)
//	ImageView ivFinger2;
	//	@Bind(R.id.iv_check1)
//	ImageView ivCheck1;
	@Bind(R.id.iv_relsult1)
	ImageView ivRelsult1;
	//	@Bind(R.id.iv_check2)
//	ImageView ivCheck2;
	@Bind(R.id.iv_relsult2)
	ImageView ivRelsult2;
	@Bind(R.id.ll_face)
	LinearLayout llFace;
	@Bind(R.id.tv_to_face)
	TextView tvToFace;
	@Bind(R.id.tv_face_result)
	TextView tvFaceResult;

	@Bind(R.id.text_title)
	TextView tvTitle;
	@Bind(R.id.button_backward)
	Button btnBack;
	private ResultPackage rcPackage;
	private int FPResult = -99;
	private SimpleDateFormat formatter;
	private String ip;
	private String local;

	//	private List<StudentInfo> studentInfos;
	private final static int MSG_PHOTO_SUCESS = 1;
	private final static int MSG_PIC1_SUCESS = 2;
	private final static int MSG_PIC1_FAIL = 3;
	private final static int MSG_PIC2_SUCESS = 4;
	private final static int MSG_PIC2_FAIL = 5;
	private final static int MSG_TO_FACE = 6;
	private Intent intent;
	private String idCard;//身份证号
	private static final int MAX_VERIFY_COUNT = 5;
	private FragmentManager manager = getSupportFragmentManager();
	private byte[] bytes_idcard;//身份证数组
	private byte[] bytes_img;//本地数组
	private byte[] btyes_finger;//指纹数组
	private byte[] bytes_photo;//现场采集数组
	private ByteImg byteImg = new ByteImg();
	private float score1;
	private float score2;
	private FragmentCamera fragmentCamera = new FragmentCamera();
	private StudentInfo studentInfo;//单个个人信息
	private Bitmap cardBitmap;//身份证照片
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_PHOTO_SUCESS:
					ivFace2.setImageBitmap(Sbitmap);
					ivFace2.setScaleType(ImageView.ScaleType.CENTER_CROP);
					break;
				case MSG_PIC1_SUCESS:
					ivRelsult1.setImageResource(R.drawable.pass);
					break;
				case MSG_PIC1_FAIL:
					ivRelsult1.setImageResource(R.drawable.nopass);
					break;
				case MSG_PIC2_SUCESS:
					ivRelsult2.setImageResource(R.drawable.pass);
					break;
				case MSG_PIC2_FAIL:
					ivRelsult2.setImageResource(R.drawable.nopass);
					break;
				case MSG_TO_FACE:
					faceResult();
					tvToFace.setVisibility(View.GONE);
					break;
				case 7:
					tvFaceResult.setText("人脸验证不通过");
					tvFaceResult.setTextColor(Color.RED);
					break;
				case 8:
					savePhotos();
					studentInfo.setRollCallState(1);
					studentInfo.setFinalRollCalltime(DateUtils.getCurrentDateTime());
					studentInfo.setFacePath(currentPhotoPath);
					DBManager.getInstance(mContext).insertResult(studentInfo);
					tvFaceResult.setText("人脸验证通过");
					tvFaceResult.setTextColor(Color.GREEN);
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							finish();
						}
					}, 3000);
					break;
				case 9:
					tvFaceResult.setText("人脸验证不通过");
					tvFaceResult.setTextColor(Color.RED);
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							finish();
						}
					}, 3000);
					break;
			}
		}
	};
	private boolean card_finger;
	private Context mContext;
	private Bitmap Sbitmap;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_distinguish_face);
		StatusBarCompat.compat(this, Color.rgb(7, 136, 242));
		card_finger = PreferencesUtils.getBoolean(Config.SETTING_CARD_FINGER, false);
		mContext = this;
		ButterKnife.bind(this);
		initObject();
		initView();
		initData();
		setListener();

	}

	@Override
	protected void initData() {
		ip = PreferencesUtils.getString(Config.TCP_IP, "");
		local = PreferencesUtils.getString(Config.TCP_PORT, "");
	}

	@Override
	protected void initView() {
		tvTitle.setText("人证核验");
		if (studentInfo != null) {
			edName.setText(studentInfo.getStudentName());
			if (PreferencesUtils.getBoolean(Content.address, true)) {
				edAddress.setText(TextUtils.isEmpty(studentInfo.getAddress()) ? "" : studentInfo.getAddress());
			}

			if (PreferencesUtils.getBoolean(Content.birthday, true)) {
				edBirthday.setText(TextUtils.isEmpty(studentInfo.getBirthday()) ? "" : studentInfo.getBirthday());
			}

			if (PreferencesUtils.getBoolean(idCar, true)) {
				edIdcard.setText(TextUtils.isEmpty(studentInfo.getIdCard()) ? "" : studentInfo.getIdCard());
			}

			if (PreferencesUtils.getBoolean(Content.nation, true)) {
				edNation.setText(TextUtils.isEmpty(studentInfo.getIdCard()) ? "" : studentInfo.getNation());
			}

			if (PreferencesUtils.getBoolean(Content.school, true)) {
				edSchool.setText(TextUtils.isEmpty(studentInfo.getSchool()) ? "" : studentInfo.getSchool());
			}

			if (PreferencesUtils.getBoolean(Content.stuId, true)) {
				edStuID.setText(TextUtils.isEmpty(studentInfo.getStudenCode()) ? "" : String.valueOf(studentInfo.getStudenCode()));
			}

			if (PreferencesUtils.getBoolean(Content.sex, true)) {
				edSex.setText(studentInfo.getSex() == 0 ? "男" : "女");
			}

			ivFace1.setImageBitmap(cardBitmap);
//			if (bytes_img != null) {
//				ivFace3.setImageBitmap(BitmapFactory.decodeByteArray(bytes_img, 0, bytes_img.length, null));
//			}
		}
//		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivFace1.getLayoutParams();
//		ivFace2.setLayoutParams(params);
//		ivFace3.setLayoutParams(params);
		if (bytes_img != null) {
			ivFace3.setImageBitmap(BitmapFactory.decodeByteArray(bytes_img, 0, bytes_img.length, null));
//			ivFace3.setImageBitmap(BitmapUtils.byteToBitmap(bytes_img));
		}
	}

	private byte[] cardfinger;

	private static final String PATH = Environment.getExternalStorageDirectory() + "/菲普莱检录系统/Photo/";

	@Override
	protected void initObject() {
		creatFile();
		intent = getIntent();
		Bundle bundle = intent.getExtras();
		idCard = bundle.getString("idCard", "");
		cardBitmap = bundle.getParcelable("bitmap");
		cardfinger = intent.getByteArrayExtra("fpinfo");
		bytes_idcard = MainMenu.getAraFaceAuthLib().getFeature(cardBitmap);
		//byte[] b2=BitmapUtils.bitmapToByte(cardBitmap);
		studentInfo = DBManager.getInstance(this).queryIdInfo(idCard);
		if (studentInfo == null) {
			studentInfo = DBManager.getInstance(mContext).queryStuInfo(idCard);
		}
		if (studentInfo == null) {
			ToastUtils.Toast(this, "查无此人");
			return;
		}
		byteImg = DBManager.getInstance(this).queryByteImg(studentInfo.getStudenCode());
		if (byteImg != null) {
			bytes_img = byteImg.getByteImg();
		}
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		if (idCard != null) {
//			studentInfos = DataDao.queryInfo(idCard);
//		} else if (studentInfo != null) {
//			studentInfos = DataDao.queryStuCode(studentInfo.getStudenCode());
//		}
		mHandler.sendEmptyMessageDelayed(MSG_TO_FACE, 2000);
	}

	private File fss;

	private void creatFile() {
		fss = new File(PATH + "Snapshot");
		if (!fss.exists()) {
			try {
				fss.mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String currentPhotoPath;

	/**
	 * 保存现场拍照图片
	 */
	private void savePhotos() {
		currentPhotoPath = studentInfo.getStudenCode() + "_" + DateUtils.getCurrentDateTime() + ".bmp";
		File fs = new File(fss, currentPhotoPath);
		if (!fs.exists()) {
			try {
				fs.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			FileOutputStream iss = new FileOutputStream(fs);
			Sbitmap.compress(Bitmap.CompressFormat.JPEG, 100, iss);
			iss.flush();
			iss.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void setListener() {
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	   /* btnStartFace.setOnClickListener(new View.OnClickListener() {
	        @Override
            public void onClick(View view) {
                faceResult();
            }
        });*/
	}

	private void getScore(byte[] b1, byte[] b2) {
		float score = MainMenu.getAraFaceAuthLib().verify(b1, b2);
		Log.i("---score---", "getScore: " + score);
	}

	/**
	 * 跳转人脸fragment页面
	 */
	private void faceResult() {
		fragmentCamera = new FragmentCamera();
//		fragmentCamera.setBytes(bytes_img);
		fragmentCamera.setBytes(bytes_idcard);
		if (byteImg != null) {
			fragmentCamera.setByte2(byteImg.getImgFeature());
		}
		CameraInterface.setVerifyCount(MAX_VERIFY_COUNT);
		FragmentTransaction transaction = manager.beginTransaction();
		transaction.add(R.id.ll_face, fragmentCamera);
		transaction.addToBackStack(null);
		transaction.commit();

	}

	private boolean FACE1RSULT = false;
	private boolean FACE2RSULT = false;

	@Override
	public void fromPic(int requestCode, int resultCode, Intent data) {
		if (requestCode == 222) {
			if (resultCode == 1) {
				score1 = data.getFloatExtra("score1", 0);//身份证和拍照比对结果
				score2 = data.getFloatExtra("score2", 0);//网照和拍照比对结果
				bytes_photo = data.getByteArrayExtra("snapshotFeature");//现场拍照照片byte数组值
//				Sbitmap = BitmapUtils.byteToBitmap(bytes_photo);
				//将现场照片byte数组转换成bitmap
				Sbitmap = ImageUtil.getRotateBitmap(
						BitmapFactory.decodeByteArray(bytes_photo, 0, bytes_photo.length), Config.displayOrientation);
//				getScore(bytes_idcard, bytes_photo);
				//ivFace2.setImageBitmap(BitmapUtils.byteToBitmap(bytes_photo));
				mHandler.sendEmptyMessage(MSG_PHOTO_SUCESS);
				Log.i("score1", "--->" + score1);
				Log.i("score2", "--->" + score2);
				//两次结果比对-1或0表示不匹配，其它值表示匹配
				if (score1 == -1 || score1 == 0) {
					mHandler.sendEmptyMessage(MSG_PIC1_FAIL);
				} else {
					FACE1RSULT = true;
					mHandler.sendEmptyMessage(MSG_PIC1_SUCESS);
				}
				if (score2 == -1 || score2 == 0) {
					mHandler.sendEmptyMessage(MSG_PIC2_FAIL);
				} else {
					FACE2RSULT = true;
					mHandler.sendEmptyMessage(MSG_PIC2_SUCESS);
				}

				//当上文传来的值不存在表示没有用到身份证，所以在此仅比对网报照片和现场拍照
				if (cardfinger == null && cardBitmap == null) {
					if (FACE2RSULT) {
						mHandler.sendEmptyMessage(8);
					} else {
						//比对成功，存储现场拍照照片
						savePhotos();
						//比对成功，存储检录状态到数据库
						studentInfo.setRollCallState(-1);
						studentInfo.setFinalRollCalltime(DateUtils.getCurrentDateTime());
						studentInfo.setFacePath(currentPhotoPath != null ? currentPhotoPath : "");
						DBManager.getInstance(mContext).insertResult(studentInfo);
						mHandler.sendEmptyMessage(9);
					}
					return;
				}
				//身份证和网照分别与现场照片比对,其中任意一个不通过，就要自动跳转到指纹识别
				if (!FACE1RSULT || !FACE2RSULT) {
					mHandler.sendEmptyMessage(7);
					final Intent intent = new Intent(mContext, DistinguishFingerActivity.class);
					intent.putExtra("fpinfo", cardfinger);
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							startActivity(intent);
							finish();
						}
					}, 2000);
				} else {
					mHandler.sendEmptyMessage(8);
				}
			} else if (resultCode == 0) {
				finish();
			}
		}
	}

	public FragmentCamera getFragment() {
		return fragmentCamera;
	}

	/**
	 * 移除fragment
	 */
	public void removeFragment() {
		if (fragmentCamera != null) {
			manager.beginTransaction().remove(fragmentCamera).commit();
		}
	}


//	public void giveValue() {
//		rcPackage.m_strBeginTime = String.valueOf(System.currentTimeMillis() / 1000);
//		//考生数量
//		rcPackage.m_nSporterNum = studentInfos.size();
//		for (int i = 0; i < rcPackage.m_nSporterNum; i++) {
//			//考生准考号
//			rcPackage.m_strSporterID[i] = studentInfo.getStudenCode();
//			//考生姓名
//			rcPackage.m_strSporterName[i] = studentInfo.getStudentName();
//			//性别
//			rcPackage.m_nGender[i] = studentInfo.getSex();
//			//检录状态
//			rcPackage.m_strSporterScoreCheck[i] = String.valueOf(studentInfo.getRollCallState());
//		}
//
//		textDate();
//		HandlerThread thread = new HandlerThread("MyHandlerThread");
//		thread.start();//创建一个HandlerThread并启动它
//		mHandler = new Handler(thread.getLooper());//使用HandlerThread的looper对象创建Handler，如果使用默认的构造方法，很有可能阻塞UI线程
//		mHandler.post(mRunnable);//将线程post到Handler中
//
//
//	}

	//上传
	Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			String datas = rcPackage.EncodePackage(new PackageHeadInfo(), false, TCPConst.enumCodeType.CodeGB2312.getIndex());
			if (ip == "" || local == "") {
				ip = "127.0.0.1";
				local = "4027";
			}
			new SocketClient().getTCPConnect(ip, Integer.parseInt(local), datas, new SocketClient.CallBackSocketTCP() {

				//返回的消息
				@Override
				public void Receive(final String info) {
					Log.e("SData:--------------->", info);
					String target = null;
					String target1 = null;
					String target2 = null;
					try {
						target1 = new String(g_SepFlag1, "GB2312");
						target2 = new String(PackageHeadInfo.g_SepFlag, "GB2312");
						target = target1 + target2;
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					String[] ArrString = info.split(target2);
					rcPackage.DecodePackage(ArrString, new ResultPackage());
				}

				@Override
				public void isConnect(boolean state) {

					if (state) {
						Log.e("连接状态-------->: ", state + "");
//                        Toast.makeText(MainCheckActivity.this, ""+state, Toast.LENGTH_SHORT).show();
					} else {
					}
				}
			});
			new SocketClient().closeSocket();
			// Log.e( "manualQuery: ",datas.toString() );
		}
	};

	public void textDate() {
		//rcPackage = new ResultPackage();
//        studentInfos = DataDao.queryAll();
//        for (int i = 0;i<studentInfos.size();i++) {
//            studentInfo = studentInfos.get(i);
//        }
		rcPackage.m_strClientName = "";
		rcPackage.m_strServerName = "";
		rcPackage.m_nEventType = String.valueOf(TCPConst.enumEvent.EventScore.getIndex());
		rcPackage.m_strPackType = "SendCheckPackage";
		rcPackage.m_strGameEventName = "";
		// rcPackage. m_nSex = 0;
		//组别如：甲组
		rcPackage.m_strSort = "";
		//项目名称如：1000米
		rcPackage.m_strEvent = "";
		//赛次，-预赛，-次赛，-复赛，-决赛
		//rcPackage. m_nLayer =0;
		//分组，如：
		// rcPackage. m_nGrp = 0;
		//项目属性1-径赛，-田高，-田远，-接力，-全能
		//rcPackage.  m_nProperty = 0;
		//全能分项名称
		rcPackage.m_strAllEventName = "";
		//全能分项属性
		//rcPackage.  m_nAllProp  = 0;
		//全能分项序号
		// rcPackage.      m_nAllNum = 0;
		//风速，如：+1.2，-0.21
		rcPackage.m_strWindSpeed = "";
		//场次
		//rcPackage.  m_nField = 0;
		//检录状态
		// rcPackage. m_nCheck = 0;
		//成绩是否确认
		// rcPackage.  m_nAffirmFlag = 0;
		//考试地址
		rcPackage.m_strExamSitePlace = "";
		//分组ID
		//rcPackage.m_nGroupType = 0;

		for (int i = 0; i < rcPackage.m_nSporterNum; i++) {
			//名次
			//rcPackage.m_nPlace[i] = 0;
			//道号
			//rcPackage.m_nTrackNO[i]= 0;
			//单位
			rcPackage.m_strUnitName[i] = "";
			rcPackage.m_strResult[i] = "";
			rcPackage.m_strNote[i] = "";


			rcPackage.m_strJudgeTime[i] = "";

			//单位代码
			rcPackage.m_strUnitCode[i] = "";
			//班级
			rcPackage.m_strClassName[i] = "";
			//考生类别
			rcPackage.m_strStudentCategory[i] = "";
			//最好成绩
			rcPackage.m_strBestScore[i] = "";
			//考试状态
			// rcPackage.m_nExamStatus[i] = 0;
		}
		for (int i = 0; i < MAX_RECORD_COUNT; i++) {
			rcPackage.m_strRecordRank[i] = "";
			rcPackage.m_strRecordResult[i] = "";
		}
	}
}
